<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="search">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="标题">
              <a-input
                placeholder="请输入标题"
                v-model="queryParams.title"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="发布人">
              <a-input
                placeholder="请输入发布人"
                v-model="queryParams.sender"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <span
              style="float: left;overflow: hidden;"
              class="table-page-search-submitButtons"
            >
              <a-button type="primary" @click="search" icon="search"
                >查询</a-button
              >
              <a-button
                type="primary"
                @click="reset"
                icon="reload"
                style="margin-left: 8px"
                >重置</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" @click="readAll" icon="book"
        >全部标注已读</a-button
      >
    </div>
    <!-- 表格区域 -->
    <a-table
      ref="TableInfo"
      bordered
      style="margin-top: 22px;"
      :rowKey="record => record.id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      :loading="loading"
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange
      }"
      @change="handleTableChange"
      :scroll="{ x: 900 }"
    >
      <span slot="action" slot-scope="text, record">
        <a @click="viewNotice(record)">查看</a>
      </span>
    </a-table>
    <message-modal ref="showMessageModal"></message-modal>
    <dynamic-notice
      ref="showDynamicNotice"
      :path="openPath"
      :formData="formData"
    />
  </a-card>
</template>

<script>
import MessageModal from "../../components/tool/MessageModal";
import DynamicNotice from "../../components/tool/DynamicNotice";

export default {
  name: "Message",
  components: { MessageModal, DynamicNotice },
  data() {
    return {
      advanced: false,
      dataSource: [],
      selectedRowKeys: [],
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ["10", "20", "30", "40", "100"],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      queryParams: {},
      loading: false,
      openPath: "",
      formData: ""
    };
  },
  computed: {
    columns() {
      return [
        {
          title: "标题",
          align: "center",
          dataIndex: "title"
        },
        {
          title: "发布人",
          align: "center",
          dataIndex: "sender"
        },
        {
          title: "发布时间",
          align: "center",
          dataIndex: "sendTime"
        },
        {
          title: "阅读时间",
          align: "center",
          dataIndex: "readTime"
        },
        {
          title: "优先级",
          align: "center",
          dataIndex: "priority",
          customRender: function(text) {
            if (text === "L") {
              return <a-tag color="blue"> 低 </a-tag>;
            } else if (text === "M") {
              return <a-tag color="orange"> 中 </a-tag>;
            } else if (text === "H") {
              return <a-tag color="red"> 高 </a-tag>;
            } else {
              return text;
            }
          }
        },
        {
          title: "阅读状态",
          align: "center",
          dataIndex: "readFlag",
          customRender: function(text) {
            if (text === "0") {
              return <a-tag color="red"> 未读 </a-tag>;
            } else if (text === "1") {
              return <a-tag color="green"> 已读 </a-tag>;
            } else {
              return text;
            }
          }
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" }
        }
      ];
    }
  },
  mounted() {
    this.fetch();
  },
  watch: {
    $route() {
      this.fetch();
    }
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    viewNotice(record) {
      this.$put("api/userMessage/updateReadFlag", {
        noticeId: record.noticeId
      }).then(r => {
        if (r.data.success) {
          this.fetch(this.queryParams);
          this.syncHeadNotice(record.noticeId);
        }
      });
      if (record.openType === "component") {
        this.openPath = record.openPage;
        this.formData = { id: record.busId };
        this.$refs.showDynamNotice.detail();
      } else {
        this.$refs.showMessageModal.detail(record);
      }
    },
    syncHeadNotice(noticeId) {
      if (typeof noticeId === "undefined") {
        noticeId = null;
      }
      this.$get("api/notice/sync", { noticeId: noticeId });
    },
    readAll() {
      const that = this;
      that.$confirm({
        title: "确认操作",
        content: "是否全部标注已读?",
        onOk: function() {
          that.$put("api/userMessage/readAll", {}).then(r => {
            if (r.data.success) {
              that.$message.success(r.data.message);
              that.fetch(that.queryParams);
              that.syncHeadNotice();
            }
          });
        }
      });
    },
    batchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning("请选择需要删除的记录");
        return;
      }
      let that = this;
      this.$confirm({
        title: "确定删除所选中的记录?",
        content: "当您点击确定按钮后，这些记录将会被彻底删除",
        centered: true,
        onOk() {
          let dictIds = that.selectedRowKeys;
          that.$delete("api/notice/" + dictIds.join(",")).then(r => {
            if (r.data.success) {
              that.$message.success("删除成功");
              that.selectedRowKeys = [];
              that.search();
            }
          });
        },
        onCancel() {
          that.selectedRowKeys = [];
        }
      });
    },
    search() {
      this.fetch({
        ...this.queryParams
      });
    },
    reset() {
      // 取消选中
      this.selectedRowKeys = [];
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent;
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent;
        this.paginationInfo.pageSize = this.pagination.defaultPageSize;
      }
      this.paginationInfo = null;
      // 重置查询参数
      this.queryParams = {};
      this.fetch();
    },
    handleTableChange(pagination) {
      this.paginationInfo = pagination;
      this.fetch({
        ...this.queryParams
      });
    },
    fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize;
        params.pageNum = this.pagination.defaultCurrent;
      }
      this.$get("api/userMessage/list", {
        ...params
      }).then(r => {
        let data = r.data.data;
        const pagination = { ...this.pagination };
        pagination.total = data.total;
        this.loading = false;
        this.dataSource = data.rows;
        this.pagination = pagination;
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../../public/less/Common";

.table-page-search-wrapper {
  .ant-form-inline {
    .ant-form-item {
      display: flex;
      margin-bottom: 24px;
      margin-right: 0;
      .ant-form-item-control-wrapper {
        flex: 1 1;
        display: inline-block;
        vertical-align: middle;
      }
      > .ant-form-item-label {
        line-height: 32px;
        padding-right: 8px;
        width: auto;
      }
      .ant-form-item-control {
        height: 32px;
        line-height: 32px;
      }
    }
  }
  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }
  .table-operator {
    margin-bottom: 18px;
    button {
      margin-right: 8px;
    }
  }
}
</style>
